package com.loper7.base.utils;

import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 输入控制
 */
public class InputUtils {

    private static Pattern patternPwd;
    private static Pattern patternMobileNum;
    private static Pattern patternEmail;

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 验证是否符合 密码规定
     *
     * @param pwd 密码
     * @return
     */
    public static boolean isPwd(String pwd) {
        if (pwd.length() > 16 || pwd.length() < 6)
            return false;
        boolean flag = false;
        try {
            if (patternPwd == null) {
                patternPwd = Pattern.compile("^[a-z0-9A-Z]{6,16}$");
            }
            Matcher matcher = patternPwd.matcher(pwd);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     *
     * @param mobiles
     * @return [0-9]{5,9}
     */
    public static boolean isMobileNum(String mobiles) {
        if (TextUtils.isEmpty(mobiles))
            return false;
        
        boolean flag = true;
        try {
            if (mobiles.length() != 11)
                return false;
//            if (patternMobileNum == null) {
//                patternMobileNum = Pattern.compile("^((13[0-9])|(15[0-9])|(14[0-9])|(17[0-9])|(18[0-9]|(19[0-9])))\\d{8}$");
//            }
//            Matcher m = patternMobileNum.matcher(mobiles);
//            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (TextUtils.isEmpty(email))
            return false;
        boolean flag = false;
        try {
            if (patternEmail == null) {
                patternEmail = Pattern.compile("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
            }
            Matcher m = patternEmail.matcher(email);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }


    /**
     * 限制文本-输入小数点后两位
     *
     * @param editText
     * @return
     */
    public static void setLimitInputDecimal(final EditText editText) {

        editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        //默认两位小数
        editText.setFilters(new InputFilter[]{new MoneyValueFilter()});
    }

    /**
     * 限制文本-设置最大长度
     *
     * @param editText
     * @return
     */
    public static void setLimitInput(final EditText editText, final TextView tvLabel, final int maxLeng) {
        tvLabel.setVisibility(View.VISIBLE);
        editText.setMaxLines(500);
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String str = editText.getText().toString();
                String current = TextUtils.isDigitsOnly(str) ? "0" : str.length() + "";
                tvLabel.setText(current + "/" + maxLeng);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    /**
     * 限制文本-输入小数点后两位
     *
     * @param editText
     * @return
     */
    public static void setLimitInputDecimal(final EditText editText, int index) {

        editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        //默认两位小数
        editText.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(index)});
    }


    /**
     * 描述   ：金额输入过滤器，限制小数点后输入位数
     * <p>
     * 默认限制小数点2位
     * 默认第一位输入小数点时，转换为0.
     * 如果起始位置为0,且第二位跟的不是".",则无法后续输入
     */
    static class MoneyValueFilter extends DigitsKeyListener {

        private static final String TAG = "MoneyValueFilter";

        public MoneyValueFilter() {
            super(false, true);
        }

        private int digits = 2;

        public MoneyValueFilter setDigits(int d) {
            digits = d;
            return this;
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            CharSequence out = super.filter(source, start, end, dest, dstart, dend);


            // if changed, replace the source
            if (out != null) {
                source = out;
                start = 0;
                end = out.length();
            }

            int len = end - start;

            // if deleting, source is empty
            // and deleting can't break anything
            if (len == 0) {
                return source;
            }

            //以点开始的时候，自动在前面添加0
            if (source.toString().equals(".") && dstart == 0) {
                return "0.";
            }
//            //如果起始位置为0,且第二位跟的不是".",则无法后续输入
//            if (!source.toString().equals(".") && dest.toString().equals("0")) {
//                return "";
//            }

            int dlen = dest.length();

            // Find the position of the decimal .
            for (int i = 0; i < dstart; i++) {
                if (dest.charAt(i) == '.') {
                    // being here means, that a number has
                    // been inserted after the dot
                    // check if the amount of digits is right
                    return (dlen - (i + 1) + len > digits) ?
                            "" :
                            new SpannableStringBuilder(source, start, end);
                }
            }

            for (int i = start; i < end; ++i) {
                if (source.charAt(i) == '.') {
                    // being here means, dot has been inserted
                    // check if the amount of digits is right
                    if ((dlen - dend) + (end - (i + 1)) > digits)
                        return "";
                    else
                        break;  // return new SpannableStringBuilder(source, start, end);
                }
            }


            // if the dot is after the inserted part,
            // nothing can break
            return new SpannableStringBuilder(source, start, end);
        }
    }

}